/*
/* author : Dinh Ngoc Tuan Vu (A0092633)
 */
package sg.edu.nus.iss.team4ft.ui;

import java.awt.BorderLayout;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import sg.edu.nus.iss.team4ft.exception.InvalidOperationException;
import sg.edu.nus.iss.team4ft.manager.CustomerAccountManager;
import sg.edu.nus.iss.team4ft.service.CustomerAccount;
import sg.edu.nus.iss.team4ft.util.AppConstant;

public class AccountSubPanel extends Panel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Mode mode;
	
	CustomerAccountManager manager = new CustomerAccountManager();
	CustomerAccount currentCustomerAccount;
	
	private JButton allCustomer = new JButton("All Customers");
	private JButton newRegistration = new JButton("New Registration");
	private JButton viewRegistration = new JButton("View Registration");
	private JButton editRegistration = new JButton("Edit Registration");
	
	private JButton save = new JButton("Save");
	private JButton cancel = new JButton("Cancel");
	
	private JPanel p = new JPanel (new GridLayout (0,1));
	private Panel bottomPan = new Panel();
	private JPanel viewWindow = new JPanel();
	
	CustomerAccountRegistration customerAccReg;
	CustomerAccountDetails customerAccDet;
	ActionListener  newRegListener = new ActionListener() {		
		@Override
		public void actionPerformed(ActionEvent e) {
			try {
				saveNewRegistraion();
			} catch (CloneNotSupportedException ex) {
				handleException(ex);
			} catch (Exception ex) {
				handleException(ex);
			}
		}
	};
	
	ActionListener cancelListener = new ActionListener(){
		public void actionPerformed(ActionEvent e){
			loadControlPosition();
			changeToViewAllCusts();
		}
	};

	public AccountSubPanel() throws CloneNotSupportedException, Exception{
		loadControls();
	}
	
	private void loadControls() throws CloneNotSupportedException, Exception {
		bottomPan = new Panel(new FlowLayout(FlowLayout.RIGHT));
		
		save.addActionListener(newRegListener);
		cancel.addActionListener(cancelListener);
	
		customerAccDet = new CustomerAccountDetails(manager.getAllCustomerAccount());
		viewWindow.add(customerAccDet);
		viewWindow.setVisible(true);
		viewWindow.setPreferredSize(new java.awt.Dimension(450, 800));
		this.setLayout(new BorderLayout());
	
		JPanel lefpanel = createButtonPanel();
		lefpanel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(0,0,0)));
		this.add("West", lefpanel);
		this.add("Center", viewWindow);
		this.add("South", bottomPan);
	}
	
	@SuppressWarnings("deprecation")
	private void changeControlToNewReg() {
		try {
			customerAccReg = new CustomerAccountRegistration(null, Mode.New);
			customerAccDet.disable();
	    	customerAccReg.setVisible(true);
	    	
	    	viewWindow.removeAll();
    		viewWindow.add(customerAccReg);
	    	viewWindow.remove(customerAccDet);
	    	
	    	bottomPan.add(save);
			bottomPan.add(cancel);
			bottomPan.setVisible(true);
			
	    	this.validate();
	    	
		} catch (Exception ex) {
			handleException(ex);
		}
    	
	}

	@SuppressWarnings("deprecation")
	private void changeToViewAllCusts() {
		if (customerAccReg != null){
			customerAccReg.disable();
		}
		customerAccDet = new CustomerAccountDetails(manager.getAllCustomerAccount());
		customerAccDet.setVisible(true);
		bottomPan.removeAll();
		
		viewWindow.removeAll();
    	viewWindow.add(customerAccDet);
    	
    	this.validate();
		
	}
	
	@SuppressWarnings("deprecation")
	private void changeToEditReg() {
		try {
			currentCustomerAccount = customerAccDet.getCustomer();
			if(currentCustomerAccount == null)
				showMessage("Please select a account!");
			else{
				customerAccReg = new CustomerAccountRegistration(currentCustomerAccount, Mode.Edit);
				customerAccDet.disable();
		    	customerAccReg.setVisible(true);
		    	
		    	viewWindow.removeAll();
		    	viewWindow.add(customerAccReg);
		    	
		    	bottomPan.removeAll();
		    	bottomPan.add(save);
				bottomPan.add(cancel);
		    	if (customerAccReg.getCustomerControl().getActivate() == true){
		    		save.setEnabled(false);
		    	}else{
		    		save.setEnabled(true);
		    	}
		    	
				bottomPan.setVisible(true);
				
		    	this.validate();
			}
		} catch (Exception ex) {
			handleException(ex);
		}
	}
	
	@SuppressWarnings("deprecation")
	private void changeToViewReg() {
		try {
			currentCustomerAccount = customerAccDet.getCustomer();
			if(currentCustomerAccount == null)
				showMessage("Please select a account!");
			else{
				customerAccReg = new CustomerAccountRegistration(currentCustomerAccount, Mode.View);
				customerAccDet.disable();
		    	customerAccReg.setVisible(true);		    	
		    	bottomPan.removeAll();
		    	viewWindow.removeAll();
		    	viewWindow.add(customerAccReg);		    	
		    	this.validate();
			}
		} catch (Exception ex) {
			handleException(ex);
		}
		
    	
	}

	public void showMessage(String text) {		
		JOptionPane.showMessageDialog(null,text);
	}
	
	private JPanel createButtonPanel () {
		loadControlPosition();
		allCustomer.setPreferredSize(new java.awt.Dimension(125, 25));
		allCustomer.setFont(new java.awt.Font("Segoe UI",1,11));
        allCustomer.addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent e) {
            	loadControlPosition();
            	changeToViewAllCusts();
            }			
        });
        newRegistration.setPreferredSize(new java.awt.Dimension(125, 25));
        newRegistration.setFont(new java.awt.Font("Segoe UI",1,11));
        newRegistration.addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent e) {
            	loadControlPosition();
            	editRegistration.setEnabled(false);
            	viewRegistration.setEnabled(false);
            	changeControlToNewReg();
            }
        });
        editRegistration.setPreferredSize(new java.awt.Dimension(125, 25));
        editRegistration.setFont(new java.awt.Font("Segoe UI",1,11));
        editRegistration.addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent e) {
            	try{
            		loadControlPosition();
            		changeToEditReg();
            		
            	}catch(Exception ex) {
    				handleException(ex);
            	}
            }

			
        });
        viewRegistration.setPreferredSize(new java.awt.Dimension(125, 25));
        viewRegistration.setFont(new java.awt.Font("Segoe UI",1,11));
        viewRegistration.addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent e) {
            	try{
            		loadControlPosition();
            		changeToViewReg();
            		
            	}catch(Exception ex) {
    				handleException(ex);
            	}
            }			
        });
        
        JPanel bp = new JPanel ();
        bp.setLayout (new BorderLayout());
        bp.add ("North", p);
        return bp;
    }
	
	public void loadControlPosition(){
		p.removeAll();
		if((AppConstant.USER.getRole()).equals(AppConstant.AGENT)){
        	p.add(allCustomer);
            p.add(new JPanel());
            p.add(viewRegistration);
            p.add(new JPanel());
        }else{        	
        	p.add(allCustomer);
            p.add(new JPanel());
            p.add(newRegistration);
            p.add(new JPanel());
            p.add(editRegistration);
            p.add(new JPanel());
            p.add(viewRegistration);
            p.add(new JPanel());
            editRegistration.setEnabled(true);
            viewRegistration.setEnabled(true);
        }
	}
	
	CustomerAccount ca;	
	private Boolean deactiveCustomer() throws CloneNotSupportedException, Exception{
		manager.deregisterCustomerAccount(ca.getCustomer().getNRIC());
		return true;
	}
	
	private void saveNewRegistraion() throws CloneNotSupportedException, Exception {
		try {
			boolean deactivate = false;
			
			ca = customerAccReg.getCustomerAccount();
			deactivate = customerAccReg.getCustomerControl().getActivate();
			
			if(deactivate == true){
				String title = "Deactivation";
		        String msg = "Do you really want to deactivate this customer ?" ;
		        
		        int value = JOptionPane.showConfirmDialog(null, msg, title, JOptionPane.YES_NO_OPTION);
		        if(value==0){
						deactiveCustomer();
						customerAccReg.getCustomerControl().changeControlState(false);
		        }
			}else{
				manager.registerCustomerAccount(ca, false);
			}	
			loadControlPosition();
        	changeToViewAllCusts();
		}catch (IOException ex) {
			handleException(ex);
		}catch (InvalidOperationException ex) {
			handleException(ex);
		}catch (Exception ex) {
			handleException(ex);
		}	
	}


	private void handleException(Exception e1) {
		e1.printStackTrace();
		String s = e1.getMessage();
		if(!s.equals(""))
			showMessage(s);
		else
			showMessage(AppConstant.ERROR);
	}

	public Mode getMode() {
		return mode;
	}
}
